package com.weifly.weistock.trade.trade.tradeX;

import com.sun.jna.Native;
import com.weifly.weistock.core.common.StockException;

/**
 * TradeX会话Factory
 *
 * @author weifly
 * @since 2021/6/8
 */
public class TradeXSessionFactory {

    private TdxLibrary tdxLibrary; // 本地dll库
    private boolean open = false; // 打开tdx，则为true
    private byte[] result = new byte[1024 * 1024]; // 调用返回结果
    private byte[] errInfo = new byte[256]; // 调用出错信息

    private synchronized void initLibrary() {
        // 加载dll
        if (this.tdxLibrary == null) {
            this.tdxLibrary = (TdxLibrary) Native.loadLibrary("TradeX2-M", TdxLibrary.class);
        }
        // 打开tdx
        if (!this.open) {
            int openResult = this.tdxLibrary.OpenTdx((short) 14, "8.27", (byte) 12, (byte) 0, errInfo);
            if (openResult < 0) {
                String msg = "打开通达信实例错误！原因是: " + Native.toString(errInfo, "GBK");
                throw new StockException(msg);
            }
            this.open = true;
        }
    }

    /**
     * 关闭Tdx
     */
    public void closeLibrary() {
        if (this.tdxLibrary != null && this.open) {
            this.tdxLibrary.CloseTdx();
            this.open = false;
        }
    }

    /**
     * 连接到行情服务器
     */
    public TradeXMarketSession connectMarket(String ip, int port) {
        this.initLibrary();
        //连接服务器
        int hqCode = this.tdxLibrary.TdxHq_Connect(ip, (short) port, this.result, this.errInfo);
        if (hqCode < 0) {
            String errMsg = "登录行情服务器失败：" + Native.toString(this.errInfo, "GBK");
            throw new StockException(errMsg);
        }
        TradeXMarketSession marketSession = new TradeXMarketSession(this, hqCode);
        return marketSession;
    }

    /**
     * 断开连接
     */
    void disconnectMarket(int hqCode) {
        this.initLibrary();
        this.tdxLibrary.TdxHq_Disconnect(hqCode);
    }

    TdxLibrary tdxLibrary() {
        return this.tdxLibrary;
    }
}
